let _baseUrl=getApp().globalData.baseUrl;

const request=function(type, url, obj, loading, msg){
	let token = uni.getStorageSync('token') || '';
	let pro = new Promise((resolve, reject) => {
		if (loading) {
			uni.showLoading({
				title: '请求中,请稍等..',
				mask:true
			});
		}
		uni.request({
			url: _baseUrl +url,
			data: obj,
			method: type,
			header: {
				'token':token,
				'x-requested-with':'XMLHttpRequest'
			},
			dataType: 'json',
			success: (res) => {
				if (loading) {
					uni.hideLoading();
				}
				if (res.statusCode == 200) {
					if (res.data.code == 1) {
						if (msg && res.data.msg) {
							setTimeout(function() {
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								});
							}, 500);
						}
						resolve(res.data.data);	
					}
					if (res.data.code == 0) {
						if (msg && res.data.msg) {
							setTimeout(function() {
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
									duration:2000
								});
							}, 500);
						}
						if(typeof res.data.data=='string' && res.data.data.startsWith('redirect:')){
							let page=res.data.data.slice(9);
							uni.reLaunch({
								url:page
							});
							return;
						}
						reject(res.data);
					}
				}
				if (res.statusCode == 401) {
					let pages = getCurrentPages();
					let currentpage = pages[pages.length - 1];
					let redict_url=currentpage.$page.fullPath;
					uni.setStorageSync('token','');
					uni.setStorageSync('userinfo','');
					// #ifdef H5
					let status = navigator.userAgent.toLowerCase();
					if (status.indexOf('micromessenger')!=-1) {
						uni.setStorageSync('redict_url',redict_url);
						location.href=_baseUrl+'mpapp/connect?action=redict';
					}else {
						uni.redirectTo({
							url:'/pages/merchant/wxlogin'
						});
					}
					// #endif
					// #ifdef MP-WEIXIN
					wx.login({
						success:res=>{
							// 发送用户信息
							post('miniapp/login', {
								code: res.code,
							},true).then(res => {
								uni.setStorageSync('userinfo', res.userinfo);																
								uni.setStorageSync('token', res.token);
								uni.reLaunch({
									url:decodeURIComponent(redict_url)
								});
							}).catch(err=>{
								uni.setStorageSync('redict_url',redict_url);
								let url=encodeURIComponent(_baseUrl+'mpapp/connect?action=miniapp');
								uni.redirectTo({
									url:'/pages/index/webview?url='+url
								});
							});
						},fail: (e) => {
							console.log(e)
						}
					});
					// #endif
				}
				if (res.statusCode == 500) {
					setTimeout(function() {
						uni.showToast({
							title: '系统错误',
							icon: 'none'
						});
					}, 500);
				}
			},
			fail: (res) => {
				if (msg) {
					uni.hideLoading();
				}
				// #ifdef MP-ALIPAY
				if(res.statusCode==401){
					let pages = getCurrentPages();
					let currentpage = pages[pages.length - 1];
					let redict_url=currentpage.$page.fullPath;
					my.getAuthCode({
					  scopes: 'auth_base',
					  success: (res) => {
						let code = res.authCode;
						// 发送用户信息
						post('alipay/login', {
							code: code,
						},true).then(res => {
							uni.setStorageSync('userinfo', res.userinfo);																
							uni.setStorageSync('token', res.token);
							uni.reLaunch({
								url:decodeURIComponent(redict_url)
							});
						});
					  },
					  fail: err => {
					    console.log('my.getAuthCode 调用失败', err)
					  }
					});
				}else{
					setTimeout(function() {
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
					}, 500);
				}
				// #endif
				// #ifndef MP-ALIPAY
				setTimeout(function() {
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}, 500);
				// #endif
				reject();
			}
		});
	});
	return pro;
}
const post = function(url, obj,loading=false,msg = false){
	return request("POST", url, obj, loading, msg)
}
const get = function(url, obj, loading=false,msg = false){
	return request("GET", url, obj, loading,msg)
}
const uploadFile=function(file,isPrivate=false) {
    let uri = "common/upload";
	if(isPrivate){
		uri = "common/upload?private=1";
	}
	let token = uni.getStorageSync('token') || '';
	let pro = new Promise((resolve, reject) => {
		uni.showLoading({
			title: '图片上传中..'
		});
		uni.uploadFile({
		  url: _baseUrl + uri,
		  filePath: file,
		  header:{
			  'token':token,
			  'x-requested-with':'XMLHttpRequest'
		  },
		  name: 'file',
		  success: function(uploadRes) {
		    if (uploadRes.statusCode === 200) {
		      let res = JSON.parse(uploadRes.data);
		      if (res.code == 1) {
		         resolve(res.data);
		      } else {
		        uni.showToast({
		          title: '上传失败',
		          icon: 'none'
		        })
		      }
		    } else {
		      uni.showToast({
		        title: '网络错误',
		        icon: 'none'
		      });
		    }
			uni.hideLoading();
		  },
		  fail:function(e){
			  reject(e);
			  uni.hideLoading();
		  }
		});
	}); 
	return pro;
}
const userinfo=function(key,value){
	let userinfo=uni.getStorageSync('userinfo') || '';
	if(!userinfo){
		return userinfo;
	}
	if(key){
		if(value){
			userinfo[key]=value;
			uni.setStorageSync('userinfo',userinfo);
		}
		return userinfo[key] || '';
	}
	return userinfo;
}

const navigateTo=function(e){
	if(typeof e=='object'){
		e='/pages/'+e.currentTarget.dataset.url;
	}else{
		e='/pages/'+e;
	}
	uni.navigateTo({
		url:e,
		fail:function(res){
			console.log(res);
		}
	});
}
const reLaunch=function(e,time=0){
	if(typeof e=='object'){
		e='/pages/'+e.currentTarget.dataset.url;
	}else{
		e='/pages/'+e;
	}
	setTimeout(()=>{
		uni.reLaunch({
			url:e,
			fail:function(res){
				console.log(res);
			}
		});
	},time)
}
const redirectTo=function(e,time=0){
	if(typeof e=='object'){
		e='/pages/'+e.currentTarget.dataset.url;
	}else{
		e='/pages/'+e;
	}
	setTimeout(()=>{
		uni.redirectTo({
			url:e,
			fail:function(res){
				console.log(res);
			}
		});
	},time)
}
const switchTab=function(e){
	if(typeof e=='object'){
		e='/pages/'+e.currentTarget.dataset.url;
	}else{
		e='/pages/'+e;
	}
	uni.switchTab({
		url:e,
		fail:(res)=>{
			console.log(res);
		}
	});
}
//time为延时1500秒执行，refresh表示是否刷新当前页面
const navigateBack=function(time,refresh=false){
	if(time instanceof Object){
		time=0;
	}
	setTimeout(res=>{
		uni.navigateBack({
			success: function () {
				let currPages = getCurrentPages();
				if(refresh){
					wx.redirectTo({
						url:currPages[currPages.length - 2].$page.fullPath
					});		
				}				
			}					
		});
	},time);
}
const msg=function(title, duration=3000, mask=false, icon='none'){
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

const platform=function(){
	// #ifdef H5
	let status = navigator.userAgent.toLowerCase();
	if (status.indexOf('micromessenger')!=-1) {
		this.platform='H5-WEIXIN';
	}else{
		this.platform='PC';
	}
	// #endif
	// #ifdef MP-WEIXIN
	this.platform='MP-WEIXIN';
	// #endif
	// #ifdef MP-ALIPAY
	this.platform='MP-ALIPAY';
	// #endif
}
export const baseUrl=_baseUrl;

export const methods={
	$platform:platform,
	$get:get,
	$post:post,
	$userinfo:userinfo,
	$uploadFile:uploadFile,
	$navigateTo:navigateTo,
	$reLaunch:reLaunch,
	$redirectTo:redirectTo,
	$switchTab:switchTab,
	$navigateBack:navigateBack,
	$msg:msg
}